import base64
import json
import os
from json import JSONDecodeError

from locust import task, FastHttpUser, constant, tag, run_single_user, events


index_cookie = 40000

def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


@events.request.add_listener
def my_request_handler(request_type, name, response_time, response_length, response,
                       context, exception, start_time, url, **kwargs):
    if exception:
        print(
            f"Request to {name} failed with exception {exception}, response_time={response_time},start_time={start_time}")
    # else:
    #     print(f"Successfully made a request to: {name}")
    #     print(f"The response was {response.text}")


class ModifyInfo(FastHttpUser):
    wait_time = constant(1)
    host = "https://www.retone-hearing.fit"
    # header = {"Content-Type": "application/json"}
    # header = {"Cookie": "hearingaid_user=NmE1YWQyZmMtZGMzZC00OGU2LWI5NTgtN2IxMzNjZjRjMDQw",
    #           "Content-Type": "application/json"}
    cookie = get_cookie()
    # default_headers = {"Content-Type": "application/json"}
    def on_start(self):
        numbers_of_user = True
        if numbers_of_user == True:
            self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
                           "Content-Type": "application/json"}
        else:
            self.header = {"Cookie": f"hearingaid_user={self.cookie}",
                           "Content-Type": "application/json"}

    # @task
    # @tag('modify_info')
    # def modify_info(self):
    #     url = '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonInfo'
    #     data = {
    #         "account": 'autotest9796',
    #         "name": 'autotest9796',
    #         "gender": 'MALE'
    #     }
    #     with self.rest("post", url, data=enconde_bs64(data), headers=self.header) as resp:
    #         try:
    #             if resp.status_code != 200 or (resp.json()['data'] == None and resp.json()["description"] is not None):
    #                 resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    #             else:
    #                 # print(resp.json())
    #                 resp.success()
    #         except JSONDecodeError:
    #             resp.failure("Response could not be decoded as JSON")
    #         except KeyError:
    #             resp.failure("Response did not contain expected key 'greeting'")

    @task
    @tag('modify_passwd')
    def modify_passwd(self):
        url = '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/modifyPersonPassword'
        data = {
            "oldPassword": 'cc1234',
            "newPassword": 'cc1234'
        }
        # print(f"cookie = {self.header}")
        with self.rest("post", url, data=enconde_bs64(data), headers=self.header) as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()["description"] is not None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # print(resp.json())
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'greeting'")


if __name__ == '__main__':
    # os.system('locust -f stress_modify.py --web-host="127.0.0.1"')
    run_single_user(ModifyInfo)
    # pass
